package preka.prefuse.action.animate;

import prefuse.action.ItemAction;
import prefuse.visual.VisualItem;
import preka.IVC;
import preka.prefuse.visual.VisualInstance;
import preka.prefuse.visual.VisualInstances;


/**
 * Animator that linearly interpolates between two positions. This
 * is useful for performing animated transitions.
 *
 * @author <a href="http://jheer.org">jeffrey heer</a>
 */
public class IVCLocationAnimator extends ItemAction {

    private boolean m_fixAtEnd;
    private VisualInstances m_visualInstances;

    /**
     * Create a new LocationAnimator that processes all data groups.
     */
    public IVCLocationAnimator() {
        super();
        m_fixAtEnd = false;
        m_visualInstances = null;
    }

    /**
     * Create a new LocationAnimator that processes the specified group.
     * @param group the data group to process.
     */
    public IVCLocationAnimator(String group) {
        super(group);
        m_fixAtEnd = false;
        m_visualInstances = null;
    }

    public IVCLocationAnimator(String group, boolean fixAtEnd, VisualInstances vinsts) {
        super(group);
        m_fixAtEnd = fixAtEnd;
        m_visualInstances = vinsts;
    }

    /**
     * @see prefuse.action.ItemAction#process(prefuse.visual.VisualItem, double)
     */
    public void process(VisualItem item, double frac) {
        //System.out.println("hey!");
        if (item.getInt(IVC.INSTANCE_ATTRIBUTE) > -1)
        {
            VisualInstance vinst = m_visualInstances.getVisualInstance(item.getInt(IVC.INSTANCE_ATTRIBUTE));
            if (vinst.isMoving()) {
                /*System.out.println("instance0: "+item.getInt(IVC.INSTANCE_ATTRIBUTE)+
                                       " X:"+item.getX()+" Y:"+item.getY()+
                                       " EndX:"+item.getEndX()+" EndY:"+item.getEndY());*/
                double sx = item.getStartX();
                double sy = item.getStartY();
                item.setX(sx + frac*(item.getEndX()-sx));
                item.setY(sy + frac*(item.getEndY()-sy));
                if (frac == 1 && m_fixAtEnd) {
                    //System.out.println("instance0: "+item.getInt(IVC.INSTANCE_ATTRIBUTE));
                    System.out.println("instance1: "+item.getInt(IVC.INSTANCE_ATTRIBUTE)+
                                       " X:"+item.getX()+" Y:"+item.getY()+
                                       " EndX:"+item.getEndX()+" EndY:"+item.getEndY());
                    vinst.setIsMoving(false);

                    item.setStartX(item.getEndX());
                    item.setStartY(item.getEndY());
                    vinst.setX(item.getX());
                    vinst.setY(item.getY());
                    item.setFixed(true);
                    vinst.setHasMoved(true);
                }
            }
        }
    }

} // end of class LocationAnimator
